extends Node
class_name CultivationSystem

# 修炼状态
enum CultivationState {
	IDLE,           # 空闲状态
	CULTIVATING,     # 修炼中
	BREAKTHROUGH,    # 突破中
	BOTTLENECK       # 瓶颈状态
}

# 当前修炼状态
var current_state: int = CultivationState.IDLE

# 修炼时间计时器
var cultivation_timer: float = 0.0
var cultivation_duration: float = 10.0  # 默认修炼时长（秒）

# 修炼效率相关
var cultivation_efficiency: float = 1.0  # 基础修炼效率
var breakthrough_chance: float = 0.1     # 基础突破几率

# 修炼资源
var spirit_stones_consumed: int = 0      # 消耗的灵石数量

# 瓶颈相关
var bottleneck_level: int = 0            # 瓶颈等级（越高越难突破）
var bottleneck_threshold: int = 3         # 瓶颈阈值（达到此值时进入瓶颈状态）

# 引用
var player: Player = null

# 信号
signal cultivation_started(duration)
signal cultivation_completed(gained_exp)
signal breakthrough_started(realm, next_realm)
signal breakthrough_succeeded(new_realm)
signal breakthrough_failed()
signal bottleneck_reached(level)

# 初始化修炼系统
func initialize(p_player: Player) -> void:
	player = p_player
	
	# 根据玩家灵根品质调整修炼效率
	_adjust_cultivation_efficiency()

# 开始修炼
func start_cultivation(duration: float = 10.0, use_spirit_stones: int = 0) -> bool:
	# 检查是否可以开始修炼
	if current_state != CultivationState.IDLE:
		return false
	
	# 检查灵石使用
	if use_spirit_stones > 0:
		if player.spirit_stones < use_spirit_stones:
			return false  # 灵石不足
		
		# 消耗灵石
		player.spirit_stones -= use_spirit_stones
		spirit_stones_consumed = use_spirit_stones
		
		# 灵石提升修炼效率
		cultivation_efficiency += use_spirit_stones * 0.01
	
	# 设置修炼时间
	cultivation_duration = duration
	cultivation_timer = 0.0
	
	# 更新状态
	current_state = CultivationState.CULTIVATING
	
	# 发出信号
	emit_signal("cultivation_started", duration)
	
	return true

# 更新修炼进度
func update(delta: float) -> void:
	match current_state:
		CultivationState.CULTIVATING:
			# 更新修炼时间
			cultivation_timer += delta
			
			# 检查修炼是否完成
			if cultivation_timer >= cultivation_duration:
				_complete_cultivation()
		
		CultivationState.BREAKTHROUGH:
			# 突破过程中不需要更新
			pass
		
		CultivationState.BOTTLENECK:
			# 瓶颈状态下不进行修炼
			pass

# 完成修炼
func _complete_cultivation() -> void:
	# 计算获得的经验值
	var base_exp = 10 * cultivation_duration / 10.0  # 每10秒10点经验
	var gained_exp = int(base_exp * cultivation_efficiency)
	
	# 玩家获得经验
	player.gain_experience(gained_exp)
	
	# 重置状态
	current_state = CultivationState.IDLE
	cultivation_timer = 0.0
	cultivation_efficiency = 1.0  # 重置为基础效率
	spirit_stones_consumed = 0
	
	# 发出信号
	emit_signal("cultivation_completed", gained_exp)
	
	# 检查是否可以突破
	_check_breakthrough()

# 检查是否可以突破
func _check_breakthrough() -> bool:
	# 检查是否处于瓶颈状态
	if current_state == CultivationState.BOTTLENECK:
		return false
	
	# 获取当前境界和下一个境界
	var current_realm = player.cultivation_realm
	var next_realm = current_realm + 1
	
	# 检查是否已达最高境界
	if current_realm >= Player.CultivationRealm.ASCENSION:
		return false
	
	# 计算突破几率
	var chance = breakthrough_chance
	
	# 根据玩家等级调整突破几率
	var level_requirement = 0
	match next_realm:
		Player.CultivationRealm.QI_REFINING_2: level_requirement = 1
		Player.CultivationRealm.QI_REFINING_3: level_requirement = 2
		Player.CultivationRealm.FOUNDATION_1: level_requirement = 3
		Player.CultivationRealm.FOUNDATION_2: level_requirement = 4
		Player.CultivationRealm.FOUNDATION_3: level_requirement = 6
		Player.CultivationRealm.CORE_FORMATION_1: level_requirement = 8
		Player.CultivationRealm.CORE_FORMATION_2: level_requirement = 10
		Player.CultivationRealm.CORE_FORMATION_3: level_requirement = 12
		Player.CultivationRealm.NASCENT_SOUL_1: level_requirement = 14
		Player.CultivationRealm.NASCENT_SOUL_2: level_requirement = 16
		Player.CultivationRealm.NASCENT_SOUL_3: level_requirement = 18
		Player.CultivationRealm.DIVINITY_1: level_requirement = 20
		Player.CultivationRealm.DIVINITY_2: level_requirement = 22
		Player.CultivationRealm.DIVINITY_3: level_requirement = 25
		Player.CultivationRealm.ASCENSION: level_requirement = 30
	
	# 如果等级不足，无法突破
	if player.level < level_requirement:
		return false
	
	# 等级越高于要求，突破几率越大
	var level_bonus = (player.level - level_requirement) * 0.05
	chance += level_bonus
	
	# 灵根品质影响突破几率
	match player.spirit_root_quality:
		Player.SpiritRootQuality.WEAK: chance -= 0.05
		Player.SpiritRootQuality.NORMAL: chance += 0.0
		Player.SpiritRootQuality.GOOD: chance += 0.05
		Player.SpiritRootQuality.EXCELLENT: chance += 0.1
		Player.SpiritRootQuality.SUPERIOR: chance += 0.15
		Player.SpiritRootQuality.SUPREME: chance += 0.2
	
	# 确保几率在合理范围内
	chance = clamp(chance, 0.01, 0.9)
	
	# 随机判断是否突破
	if randf() < chance:
		# 开始突破
		_start_breakthrough(current_realm, next_realm)
		return true
	else:
		# 增加瓶颈计数
		bottleneck_level += 1
		
		# 检查是否进入瓶颈状态
		if bottleneck_level >= bottleneck_threshold:
			_enter_bottleneck()
		
		return false

# 开始突破
func _start_breakthrough(current_realm: int, next_realm: int) -> void:
	# 更新状态
	current_state = CultivationState.BREAKTHROUGH
	
	# 发出信号
	emit_signal("breakthrough_started", current_realm, next_realm)
	
	# 突破成功
	_complete_breakthrough(next_realm)

# 完成突破
func _complete_breakthrough(new_realm: int) -> void:
	# 更新玩家境界
	player.cultivation_realm = new_realm
	
	# 更新玩家属性
	player._update_stats()
	
	# 重置瓶颈
	bottleneck_level = 0
	
	# 恢复状态
	current_state = CultivationState.IDLE
	
	# 发出信号
	emit_signal("breakthrough_succeeded", new_realm)

# 进入瓶颈状态
func _enter_bottleneck() -> void:
	# 更新状态
	current_state = CultivationState.BOTTLENECK
	
	# 发出信号
	emit_signal("bottleneck_reached", bottleneck_level)

# 尝试突破瓶颈
func attempt_bottleneck_breakthrough(use_spirit_stones: int = 0, use_special_item: bool = false) -> bool:
	# 检查是否处于瓶颈状态
	if current_state != CultivationState.BOTTLENECK:
		return false
	
	# 基础突破几率
	var chance = 0.1
	
	# 使用灵石增加几率
	if use_spirit_stones > 0:
		if player.spirit_stones < use_spirit_stones:
			return false  # 灵石不足
		
		# 消耗灵石
		player.spirit_stones -= use_spirit_stones
		chance += use_spirit_stones * 0.005  # 每个灵石增加0.5%几率
	
	# 使用特殊物品增加几率
	if use_special_item:
		# 这里应该检查玩家是否有特殊物品并消耗它
		# 简化版本直接增加几率
		chance += 0.2
	
	# 几率上限
	chance = min(chance, 0.9)
	
	# 随机判断是否突破瓶颈
	if randf() < chance:
		# 突破瓶颈成功
		bottleneck_level = 0
		current_state = CultivationState.IDLE
		return true
	else:
		# 失败但减少瓶颈等级
		bottleneck_level = max(1, bottleneck_level - 1)
		return false

# 根据玩家灵根品质调整修炼效率
func _adjust_cultivation_efficiency() -> void:
	if not player:
		return
	
	# 灵根数量影响（单灵根效率最高）
	var root_count = player.spirit_roots.size()
	if root_count == 1:
		cultivation_efficiency *= 1.5
	elif root_count == 2:
		cultivation_efficiency *= 1.3
	elif root_count == 3:
		cultivation_efficiency *= 1.1
	elif root_count == 4:
		cultivation_efficiency *= 0.9
	elif root_count == 5:
		cultivation_efficiency *= 0.8
	
	# 灵根品质影响
	match player.spirit_root_quality:
		Player.SpiritRootQuality.WEAK:
			cultivation_efficiency *= 0.7
		Player.SpiritRootQuality.NORMAL:
			cultivation_efficiency *= 1.0
		Player.SpiritRootQuality.GOOD:
			cultivation_efficiency *= 1.2
		Player.SpiritRootQuality.EXCELLENT:
			cultivation_efficiency *= 1.5
		Player.SpiritRootQuality.SUPERIOR:
			cultivation_efficiency *= 2.0
		Player.SpiritRootQuality.SUPREME:
			cultivation_efficiency *= 3.0

# 获取修炼状态名称
func get_state_name() -> String:
	match current_state:
		CultivationState.IDLE:
			return "空闲"
		CultivationState.CULTIVATING:
			return "修炼中"
		CultivationState.BREAKTHROUGH:
			return "突破中"
		CultivationState.BOTTLENECK:
			return "瓶颈"
		_:
			return "未知"

# 获取当前修炼进度百分比
func get_cultivation_progress() -> float:
	if current_state != CultivationState.CULTIVATING or cultivation_duration <= 0:
		return 0.0
	
	return min(cultivation_timer / cultivation_duration, 1.0) * 100.0
